package socket.httpserver.singlefile;

import java.io.IOException;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class RunSingleFileHttpServer {
    public static void main(String[] args) {
        int port;
        try{
            port = Integer.parseInt(args[1]);
            if(port < 1 || port > 65535) {
                port = 80;
            }
        } catch (RuntimeException e) {
            port = 80;
        }

        String encoding = "UTF-8";
        if(args.length > 2) {
            encoding = args[2];
        }

        try {
            Path path = Paths.get(args[0]);
            byte[] data = Files.readAllBytes(path);

            String contentType = URLConnection.getFileNameMap().getContentTypeFor(args[0]);
            SingleFileHTTPServer server = new SingleFileHTTPServer(data, encoding, contentType, port);

            server.start();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(
                    "Usage: java SingleFileHTTPSerever filename port encoding"
            );
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
